import axios from 'axios'
import { Notify, Toast } from 'vant'
import router from '../router'
export function request(config) {
  const instance = axios.create({
    baseURL: 'https://api.shop.eduwork.cn',
    timeout: 5000
    // headers: headers
  })
  // 请求拦截
  instance.interceptors.request.use(
    config => {
      // Do something before request is sent
      // 如果有一些接口需要认证才可以访问,就在这里统一设置
      if (localStorage.getItem('token')) {
        config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token')
      }
      // 直接放行
      return config
    },
    error => {
      // Do something with request error
      return Promise.reject(error)
    }
  )
  // 响应拦截
  instance.interceptors.response.use(
    response => {
      // Do something before response is sent
      return response.data ? response.data : response
    },
    error => {
      if (error.response.status === 401) {
        Toast.fail('请先登录')
        router.push('/login')
      }
      // Do something with response error
      // 如果有需要授权才可以访问的接口,统一去login授权
      const errorArr = Object.keys(error.response.data.errors)
      Notify({ type: 'danger', message: error.response.data.errors[errorArr[0]][0] })
      // 如果有错误,这里面会去处理,显示错误信息
      return Promise.reject(error)
    }
  )

  return instance(config)
}
